package com.tencent.qf.activity.special.area.service.service.Impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.tencent.qf.activity.special.area.service.config.SpecialAreaConfig;
import com.tencent.qf.activity.special.area.service.dto.ActExtInfo;
import com.tencent.qf.activity.special.area.service.service.JdGiftCouponTransferInfoService;
import com.tencent.qf.activity.speical.area.api.dto.JdGiftCouponTransferCountDTO;
import com.tencent.qf.activity.speical.area.api.dto.JdGiftCouponTransferInfoDTO;
import com.tencent.qf.activity.speical.area.api.dto.req.SpecialAreaCouponRequest;
import com.tencent.qf.activity.speical.area.api.dto.req.SpecialAreaTransferRequest;
import com.tencent.qf.activity.speical.area.api.dto.resp.SpecialAreaCouponResponse;
import com.tencent.qf.activity.speical.area.api.service.SpecialAreaService;
import com.tencent.qf.common.activityplatform.ActivityPlatformUtils;
import com.tencent.qf.common.activityplatform.ActivityPlatfromApiPath;
import com.tencent.qf.common.exception.ErrorCode;
import com.tencent.qf.common.exception.ServiceException;
import com.tencent.qf.common.gateway.activitymanager.ActivityManagerService;
import com.tencent.qf.common.gateway.activitymanager.DTO.SpecialAreaGoodsConfigDTO;
import com.tencent.qf.common.gateway.qwRobot.QwRobotService;
import com.tencent.qf.common.pojo.ActivityPlatformHttpResult;
import com.tencent.qf.common.pojo.HttpResult;
import com.tencent.qf.common.redis.RedisKeyConstants;
import com.tencent.qf.common.util.DateUtils;
import com.tencent.qf.user.config.properties.UserInfoProperties;
import com.tencent.qf.user.dto.UserInfoDetail;
import com.tencent.qf.user.dto.request.UserInfoByUidUnionIdRequest;
import com.tencent.qf.user.dto.request.UserPaymentInfoIncludeJdGiftCouponReq;
import com.tencent.qf.user.dto.response.UserPaymentCountDTO;
import com.tencent.qf.user.dto.response.UserTagInfo;
import com.tencent.qf.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author p_jongzheng@tencent.com
 * @create 2023/8/11 17:15
 * @description:
 */

@Slf4j
@Service
public class SpecialAreaServiceImpl implements SpecialAreaService {

    @Resource
    private ActivityPlatformUtils activityPlatformUtils;

    @Resource
    private JdGiftCouponTransferInfoService jdGiftCouponTransferInfoService;

    @Resource
    private SpecialAreaConfig specialAreaConfig;

    @Resource
    private ActivityManagerService activityManagerService;

    @Resource
    private UserService userService;


    @Resource
    private UserInfoProperties userInfoProperties;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private QwRobotService qwRobotService;

    /**
     * 查询用户在专区是否有资格领取优惠券资格（京享礼券）
     * 1. 查询用户信息，携带到 C 端
     * 2. 发起请求
     * @param specialAreaCouponRequest
     * @return
     */
    @Override
    public SpecialAreaCouponResponse querySpecialAreaUserQualification(SpecialAreaCouponRequest specialAreaCouponRequest) {

        // 查询用户信息
        this.queryUserInfo(specialAreaCouponRequest);

        // 发起请求
        try {
            String response = activityPlatformUtils.post(specialAreaCouponRequest, ActivityPlatfromApiPath.queryUserTransferQualification);
            if (!StringUtils.hasText(response)) {
                log.info("查询用户专区转链资格，签到平台响应参数为空，irisUid:{},specialKey:{}", specialAreaCouponRequest.getIrisUid(), specialAreaCouponRequest.getSpecialAreaKey());
                throw new ServiceException(ErrorCode.INTERNAL_SERVER_ERROR);
            }
            ActivityPlatformHttpResult<SpecialAreaCouponResponse> httpResult = JSON.parseObject(response, new TypeReference<ActivityPlatformHttpResult<SpecialAreaCouponResponse>>() {
            });

            if (Objects.nonNull(httpResult.getData())) {
                SpecialAreaCouponResponse couponResponse = httpResult.getData();
                return couponResponse;
            } else {
                log.info("查询用户专区转链资格，签到平台返回响应参数body为空，irisUid:{},specialKey:{}", specialAreaCouponRequest.getIrisUid(), specialAreaCouponRequest.getSpecialAreaKey());
                throw new ServiceException(Integer.valueOf(httpResult.getCode()), httpResult.getMsg());
            }
        } catch (Exception e) {
            log.error("查询用户专区转链资格 irisUid：{},specialKey：{} 报错", specialAreaCouponRequest.getIrisUid(), specialAreaCouponRequest.getSpecialAreaKey(), e);
            throw new ServiceException(ErrorCode.TOO_MANY_REQUESTS);
        }
    }

    /**
     * 查询用户相关信息
     * 1. 查询用户的转链记录
     * 2. 每日专区配置转链次数
     * 3. 用户分成信息
     * 4. 用户等级
     * 5. 用户标签
     *
     * @param specialAreaCouponRequest
     */
    private void queryUserInfo(SpecialAreaCouponRequest specialAreaCouponRequest) {
        /**
         * 查询用户的转链记录
         */
        List<JdGiftCouponTransferInfoDTO> jdGiftCouponTransferInfos = jdGiftCouponTransferInfoService.getTransferInfo(specialAreaCouponRequest.getSpecialAreaKey()
                , specialAreaCouponRequest.getIrisUid());
        specialAreaCouponRequest.setUserCouponLinkedInfoRecords(jdGiftCouponTransferInfos);
        /**
         * 每日专区配置转链次数
         */
        JdGiftCouponTransferCountDTO transferCountDTO = jdGiftCouponTransferInfoService.getTransferCount(specialAreaCouponRequest.getSpecialAreaKey(), DateUtils.getCurrentDayFirstSecondTime());
        specialAreaCouponRequest.setJdGiftCouponTransferCountDTO(transferCountDTO);

        /**
         * 用户分成信息
         */
        UserPaymentInfoIncludeJdGiftCouponReq jdGiftCouponReq = new UserPaymentInfoIncludeJdGiftCouponReq();
        jdGiftCouponReq.setUid(specialAreaCouponRequest.getIrisUid());
        jdGiftCouponReq.setUnionId(specialAreaCouponRequest.getUnionId());
        UserPaymentCountDTO userPaymentCountDTO = userService.userPaymentInfoIncludeJdGiftCoupon(jdGiftCouponReq);
        specialAreaCouponRequest.setUserPaymentCountDTO(userPaymentCountDTO);
        /**
         * 用户等级查询
         */
        UserInfoByUidUnionIdRequest userInfoByUidUnionIdReq = new UserInfoByUidUnionIdRequest();
        userInfoByUidUnionIdReq.setSaasId(userInfoProperties.getRootSaasId());
        userInfoByUidUnionIdReq.setUid(specialAreaCouponRequest.getIrisUid());
        userInfoByUidUnionIdReq.setUnionId(specialAreaCouponRequest.getUnionId());
        HttpResult<UserInfoDetail> userInfoDetailHttpResult = userService.userInfoByUidUnionId(userInfoByUidUnionIdReq);
        UserInfoDetail data = userInfoDetailHttpResult.getData();
        if (Objects.nonNull(data)) {
            specialAreaCouponRequest.setLevelId(data.getLevelId());
        }
        /**
         *  用户标签
         */
        List<UserTagInfo> userTagInfos = userService.userTags(specialAreaCouponRequest.getUnionId(), userInfoProperties.getRootSaasId());
        if (!CollectionUtils.isEmpty(userTagInfos)) {
            List<String> userTags = userTagInfos.stream().map(UserTagInfo::getTagId).distinct().collect(Collectors.toList());
            specialAreaCouponRequest.setUserTags(userTags);
        }
        /**
         * 用户账户类型
         */
        UserInfoByUidUnionIdRequest userInfoByUidUnionIdRequest = new UserInfoByUidUnionIdRequest();
        userInfoByUidUnionIdRequest.setSaasId(userInfoProperties.getRootSaasId());
        userInfoByUidUnionIdRequest.setUid(specialAreaCouponRequest.getIrisUid());
        userInfoByUidUnionIdRequest.setUnionId(specialAreaCouponRequest.getUnionId());
        HttpResult<UserInfoDetail> userInfoDetail = userService.userInfoByUidUnionId(userInfoByUidUnionIdRequest);
        if (Objects.nonNull(userInfoDetail.getData())) {
            specialAreaCouponRequest.setUserType(userInfoDetail.getData().getType());
        }
    }

    @Override
    @Async("asyncSpecialAreaExecutor")
    public void specialAreaTransferPush(SpecialAreaTransferRequest request) {
        log.info("specialAreaTransferPush-param={}", JSON.toJSONString(request));
        ActExtInfo actExtInfo = JSONObject.parseObject(request.getActExtInfo(), ActExtInfo.class);

        // 获取商品配置
        SpecialAreaGoodsConfigDTO specialAreaGoods = activityManagerService.getSpecialAreaGoods(actExtInfo.getSpecialGoodsId());

        // 获取今日转链次数
        Long goodsTransferCount = jdGiftCouponTransferInfoService.getGoodsTransferCount(actExtInfo.getSpecialGoodsId(), DateUtils.getCurrentDayFirstSecondTime());

        Double usedPercentage = (double)goodsTransferCount / specialAreaGoods.getChainTransferDayLimit() * 100 ;
        // 获取告警阈值
        String[] alarmThresholds = specialAreaConfig.getAlarmThreshold().split(",");
        for (String alarmThreshold : alarmThresholds) {
            String redisKey = String.format(RedisKeyConstants.SPECIAL_AREA_TRANSFER_LIMIT,alarmThreshold, DateUtils.getYearAndMonthAndDay());
            // 超过阈值并且没有发送过告警
            if (usedPercentage >= Integer.valueOf(alarmThreshold)){
                if(!redisTemplate.hasKey(redisKey)) {
                    redisTemplate.opsForValue().set(redisKey, "1", 1, TimeUnit.DAYS);
                    boolean success = qwRobotService.sendTransferAlarm(specialAreaGoods.getGoodsName(), specialAreaGoods.getChainTransferDayLimit(),
                            goodsTransferCount,  100 - usedPercentage.intValue());
                    // 发送失败，取消缓存标识
                    if (!success) {
                        redisTemplate.delete(redisKey);
                    }
                }
            }else{
                break;
            }
        }

    }
}
